using System;
using System.Threading;
using OpenQA.Selenium;

namespace YatFram.Browser.Selenium
{
    public class PossibleElement
    {
        private Func<IWebElement> future;
        private IWebElement innerElement;

        public PossibleElement(Func<IWebElement> element)
        {
            future = element;
        }

        public IWebElement InnerElement
        {
            get
            {
                if (innerElement == null)
                    innerElement = future();

                return innerElement;
            }
        }

        public IWebElement WaitUntilExists()
        {
            var startTime = DateTime.Now;

            while (!Exists() && ((DateTime.Now - startTime) < new TimeSpan(0, 0, 30)))
                Thread.Sleep(100);

            return InnerElement;
        }

        private IWebElement Force()
        {
            return future();
        }

        public bool Exists()
        {
            try
            {
                return InnerElement.TagName != null;
            }
            catch (Exception)
            {
                return false;
            }

        }
    }
}